<!-- 详情页主体组件 -->
<template>
  <div class="detail-main">
    <div class="sidebar">
      <div 
        :class="'sidebar-item'+(currentTab===item.tab?' sidebar-item-active':'')" 
        v-for="item in tabList" 
        :key="item.tab" 
        @click="handleTabClick(item.tab)">{{item.name}}
      </div>
    </div>
    <div class="product">
      <DetailProduct v-for="item in productList" :key="item._id" :product="item" :shopId="shopId"></DetailProduct>
    </div>
  </div>
</template>

<script>
import { ref,watchEffect } from 'vue';
import { useStore } from 'vuex'
import { useRoute } from 'vue-router';
import { get } from '@/utils/request';
import { PRODUCT } from '@/api/interface';
import DetailProduct from './detailProduct'
// 侧边栏
const useSidebar = () => {
  const currentTab = ref('all');
  const tabList = [
    {name:'全部商品',tab:'all'},
    {name:'秒杀',tab:'seckill'},
    {name:'新鲜水果',tab:'fruit'}
  ]
  const handleTabClick = (tab) => {
    currentTab.value = tab;
  }
  return {currentTab,tabList,handleTabClick}
}
// 获取商品数据
const useRequest = (id,currentTab,state) => {
  const productList = ref([]);
  const storeProduct = state.cartList[id]; 
  // 发送请求
  watchEffect(()=>{
    get(PRODUCT.replace(':id',id),{tab:currentTab.value})
    .then(response => {
      productList.value = response.data;
      // 处理数据
      for(let [index,item] of productList.value.entries()){
        storeProduct && storeProduct[item._id] && (productList.value[index] = storeProduct[item._id])
      }
    })
    .catch(error => console.log(error))
  })
  return {productList}
}
// composition
export default {
  name:'detailMain',
  components:{DetailProduct},
  setup(){
    const route = useRoute();
    const store = useStore();
    const shopId = route.params.id
    const {currentTab,tabList,handleTabClick} = useSidebar()
    const {productList} = useRequest(shopId,currentTab,store.state)
    return {productList,currentTab,tabList,handleTabClick,shopId}
  }
}
</script>

<style scoped lang="scss">
@import '@/styles/theme.scss';
.detail-main{
  width: 100%;
  height: 100%;
  display: flex;
  .sidebar{
    width: 20.2667vw;
    height: 100%;
    overflow-y: auto;
    background-color: #f5f5f5;
    &-item{
      height: 10.6667vw;
      line-height: 10.6667vw;
      text-align: center;
      font-size: 14px;
      color: $theme-font-color;
    }
    &-item-active{
      background-color: $white;
    }
  }
  .product{
    flex: auto;
    height: 100%;
    overflow-y: auto;
    padding: 0 18px 0 16px;
  }
}
</style>
